<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/21 0021
 * Time: 下午 10:37
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Model\CaseClassify;
use App\Model\ExceedShop;
use App\Model\Factory;
use App\Model\GroupList;
use App\Model\GroupMember;
use App\Model\ShoppingGoods;
use App\Model\StoresCenterGoods;
use App\Model\VideoCase;
use Illuminate\Http\Request;
use App\Model\ShopGoods;
use App\Model\ShopGoodsImg;
use App\Model\ShopGoodsClassify;
use App\Model\GoodsSpecsVal;
use App\Model\GoodsSpecsName;
use  Illuminate\Support\Facades\Redis;
use Log;
use Auth;

class GoodsController extends BaseController
{
    /**
     * 商品列表
     */
    public function Index()
    {
        return view('Admin.shop');
    }

    /**
     * 商品规格页面
     */
    public function specs()
    {
        return view('Admin.specs');
    }


    /**
     * 添加商品
     */
    public function addGoods()
    {
        return view('Admin.addGoods');
    }

    /**
     * 商品表
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function goods(Request $request)
    {
        $data = $request->all();
//        var_dump($data);exit;
        switch ($data['class']){
            case 'select': //查询
                $where['type'] = 1;
                $keyword = empty($data['keyword'])?0:$data['keyword'];
                if ($keyword['status']) {
                    $where['status'] = $keyword['status'];
                }
                if ($keyword['cid'] != '' ) {
                    $where['cid'] = $keyword['cid'];
                }
                if ( $keyword['two_tid'] != '' && $keyword['cid'] != '' ) {
                    $where['two_tid'] = $keyword['two_tid'];
                }
                $goodsname = empty($keyword['keyword'])?'':$keyword['keyword'];
                $table = ShopGoods::orderBy('sorting')->where($where);
                if($goodsname){
                    $table->where('goodsname','like','%'.$goodsname.'%');
                }
                $goods= $table->orderBy('cid','asc')->paginate(15);

                $Classify = ShopGoodsClassify::get()->toArray();
                //商品类别
                $time=[];
                if (!empty($goods)) {
                    foreach ($goods as $key => $value) {
                        $goods[$key]['classify'] = ShopGoodsClassify::where( ['id' => $value['cid'] ] )->value("name");
                        $time[$key]=[
                            'time'=>$goods[$key]['startTime'],
                            'price'=>$goods[$key]['timeprice'],
                            'rulingprice'=>$goods[$key]['rulingprice'],
                        ];
                        if ( $value['two_tid'] != "" ) {
                            $goods[$key]['classifys'] = ShopGoodsClassify::where( ['id' => $value['two_tid'] ] )->value("name");
                        } else {
                            $goods[$key]['classifys'] = "暂无二级分类";
                        }
                        $startTime=strtotime($goods[$key]['startTime']);
//                        var_dump($startTime);
                        if($startTime){
//                           $create_time = 1560666560;// 开始时间 2019-06-16 14:29:20
                            //开始日期第二天
//                            $date  =   mktime(0,0,0,date("m",$startTime),date("d",$startTime)+1,date("Y",$startTime));
                            $day =   ceil((time() - $startTime)/(3600*24));//当前天数-开始第二日 向上取整  + 1 得出活动开始天数  = 3
//                            var_dump($day);
                            $price = json_decode($time[$key]['price']);
                            $up=count($price);
                            if($day > $up || $day <=0){
                                $goods[$key]['rulingprice'] = $goods[$key]['originalprice'];
                            }else{
                                $goods[$key]['rulingprice'] = $price[$day-1] ;
                            }

                        }

                    }
                }
//                var_dump($goods);exit;

                if ($goods){
                    return ['code'=>1,'data'=>$goods];
                } else {
                    return ['code'=>0,'data'=>'没有数据'];
                }
                break;
            case 'add':    //添加 or 修改
                if ((!empty($data['imgType']) && empty($data['goodsId'])) || !empty($_FILES['myFile'])){
                    if (empty($data['goodsId']) && empty($_FILES['myFile'])){
                        return ['code'=>0,'data'=>'请上传轮播图!'];
                    }
                }
//                if (empty($data['goodsname']) ){
//                    return ['code'=>0,'data'=>'商品名称不能为空'];
//                }
//                if (empty($data['originalprice']) ){
//                    return ['code'=>0,'data'=>'商品原价不能为空'];
//                }
//                if (empty($data['rulingprice']) ){
//                    return ['code'=>0,'data'=>'商品现价不能为空'];
//                }
//                if (empty($data['costprice']) ){
//                    return ['code'=>0,'data'=>'商品奖励波比不能为空'];
//                }
//                if (empty($data['pk_integral']) ){
//                    return ['code'=>0,'data'=>'商品pk积分值不能为空'];
//                }
//                if (empty($data['goods_thumb']) ){
//                    return ['code'=>0,'data'=>'商品封面图不能为空'];
//                }

                if ($data['goods']['id']) {    //修改
                    if (empty($data['goods']['rotation_chart'])) {
                        unset($data['goods']['rotation_chart']);
                    }else{
                        $data['goods']['rotation_chart']=json_encode($data['goods']['rotation_chart']);
                    }
                    $data['goods']['timeprice']= json_encode($data['goods']['timeprice']);
                    $Rows = ShopGoods::where('id',$data['goods']['id'])->update($data['goods']);
                } else {
                    $data['goods']['rotation_chart']=json_encode($data['goods']['rotation_chart']);
                    $data['goods']['timeprice']= json_encode($data['goods']['timeprice']);
                    $data['goods']['createtime'] = time();
//                    var_dump($data);exit;
                    $Rows = ShopGoods::create($data['goods']);
//                      Redis::set("goods",$Rows);
                }
//                //更新图片
//                $goodsId = empty($data['goods']['id'])?$Rows->id : $data['goods']['id'];
//                $goodsImgName = empty($data['goodsImgName'])?0:$data['goodsImgName'];
//                $rico = $this->updateImg($goodsId,$goodsImgName);
//                var_dump($Rows);exit;
                if ($Rows ){
                    return ['code'=>1,'data'=>'设置成功'];
                } else {
                    return ['code'=>0,'data'=>'设置失败'];
                }
                break;
            case 'find':   //查询一条数据
                $goods = ShopGoods::where('id',$data['id'])->first();
                $goods['rotation_chart']=json_decode($goods['rotation_chart']);
                $cids = ShopGoodsClassify::where( ['pid' => 0 ] )->get()->toArray();
                $two_tids = ShopGoodsClassify::where( ['pid' => $goods['cid'] ] )->get()->toArray();
//                $goodsImgName = ShopGoodsImg::where('gid',$data['id'])->select('img')->get()->toArray();
                if ($goods){
                    return ['code'=>1,'data'=>['goods'=>$goods, 'two_tids' => $two_tids, 'cids' => $cids]];
                } else {
                    return ['code'=>0,'data'=>'设置失败'];
                }
                break;
            case 'delete': //删除
                if ($data['id']) {
                    
                         $rico = ShopGoods::where('id',$data['id'])->update(['type' => -1]);
                         if ($rico){
                             return ['code'=>1,'data'=>'删除成功'];
                         } else {
                             return ['code'=>0,'data'=>'删除失败'];
                         }


                } else {
                    return ['code'=>0,'data'=>'数据错误'];
                }
                break;

            case 'specs': //查出对应商品的所以规格名和对应的所有规格值
                if ( $data['id'] ) {
                    //查出该商品对应的所有规格名
                    $GoodsSpecsName = GoodsSpecsName::where( [ 'goods_id' => $data['id'] ] )->select( 'id', 'name' )->get()->toArray();
                    //查出该商品的所有规格值
                    $GoodsSpecsVal = [];
                    if ( $GoodsSpecsName ) {
                        foreach ( $GoodsSpecsName as $k => $v ) {
                            $thisSpecsVal = GoodsSpecsVal::where( [ 'specs_id' => $v['id'] ] )->select( 'id', 'val', 'specs_id' )->get()->toArray();
                            array_push( $GoodsSpecsVal, [ 'specs_id' => $v['id'], 'vals' => $thisSpecsVal ] );
                        }
                    }
                    return [ 'code' => 1, 'GoodsSpecsName' => $GoodsSpecsName, 'GoodsSpecsVal' => $GoodsSpecsVal ];
                } else {
                    return ['code'=>0,'data'=>'数据错误'];
                }
                break;
            case 'memberLevel':
                $levelData = ExceedShop::select('id','vip_name')->get()->toArray();
                if (!empty($levelData)){
                    return ['code' => 1,'data' => $levelData];
                } else {
                    return ['code' => 0,'data' => '会员等级返回失败'];
                }
                break;
            case 'saveSpecsName': //添加商品规格名
                if ( $data['goods_id'] == "" ) {
                    return ['code'=>0,'data'=>'商品id不能为空!'];
                }
                if ( $data['name'] == "" ) {
                    return ['code'=>0,'data'=>'添加规格名不能为空!'];
                }
                $specsDataSave = GoodsSpecsName::create( [ 'goods_id' => $data['goods_id'], 'name'=> $data['name'], 'addtime' => time() ] );
                if ( $specsDataSave ) {
                    return ['code'=>1,'data'=>'添加成功!'];
                } else {
                    return ['code'=>0,'data'=>'添加失败!'];
                }
                break;
            case 'saveSpecsVal': //添加规格名下的规格值
                if ( $data['specs_id'] == "" ) {
                    return ['code'=>0,'data'=>'添加的商品规格名id不能为空!'];
                }
                if ( $data['val'] == "" ) {
                    return ['code'=>0,'data'=>'添加规格值不能为空!'];
                }
                $specsDataSave = GoodsSpecsVal::create( [ 'specs_id' => $data['specs_id'], 'val' => $data['val'], 'addtime' => time() ] );
                if ( $specsDataSave ) {
                    return ['code'=>1,'data'=>'添加成功!'];
                } else {
                    return ['code'=>0,'data'=>'添加失败!'];
                }
                break;
            case 'delSpecsName': //删除商品规格名及其下面的所有规格值
                if ( $data['id'] == "" ) {
                    return ['code'=>0,'data'=>'删除规格名id不能为空!'];
                }
                $specsDatadel = GoodsSpecsName::where( [ 'id' => $data['id'] ] )->delete();
                if ( $specsDatadel ) {
                    GoodsSpecsVal::where( [ 'specs_id' => $data['id'] ] )->delete();
                    return ['code'=>1,'data'=>'删除成功!'];
                } else {
                    return ['code'=>0,'data'=>'删除失败!'];
                }
                break;
            case 'delSpecsVal': //删除对应规格名下的规格值
                if ( $data['id'] == "" ) {
                    return ['code'=>0,'data'=>'删除规格值id不能为空!'];
                }
                $specsDatadel = GoodsSpecsVal::where( [ 'id' => $data['id'] ] )->delete();
                if ( $specsDatadel ) {
                    return ['code'=>1,'data'=>'删除成功!'];
                } else {
                    return ['code'=>0,'data'=>'删除失败!'];
                }
                break;
        }
    }

    /**
     * 商品图片路径
     * @param int $gid
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    public function updateImg($gid = 0,$data = array())
    {
        if ($gid > 0) {
           ShopGoodsImg::where('gid',$gid)->delete();
        }
        $rico = '';
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $rico = ShopGoodsImg::create(['gid'=>$gid,'img'=>$v]);
            }
        }
        if ($rico) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *案例分类列表
     */
    public function caseClassifyList(){

        return view('Admin.case_classify.index');
    }
    /**
     *案例分类添加
     */
    public function caseClassifyAdd(){

        return view('Admin.case_classify.add');
    }

    /**
     *案例分类数据接口
     */
    public function caseClassify(Request $request)
    {
        $data = $request->all();
        $caseClassifyModel = new CaseClassify();
        switch ($data['class']) {
            case 'select':
                $classify = $caseClassifyModel->orderBy('id', 'desc')->paginate(15);
                if ($classify) {
                    return ['code' => 1, 'data' => $classify];
                } else {
                    return ['code' => 0, 'data' => '暂无分类'];
                }
                break;
            case 'find':
                if (isset($data['id'])) {
                    $detail = $caseClassifyModel->where('id', $data['id'])->first();
                    if ($detail) {
                        return ['code' => 1, 'data' => $detail];
                    } else {
                        return ['code' => 0, 'data' => '分类不存在'];
                    }
                }
                break;
            case 'add':
                if (empty($data['classify']['name'])) {
                    return ['code' => 0, 'data' => '分类名不能为空'];
                }
                if (empty($data['classify']['sort'])){
                    return ['code' => 0,'data' => '请添加排序'];
                }
                if (empty($data['classify']['detail'])) {
                    return ['code' => 0, 'data' => '分类详情不能为空'];
                }
                $data['classify']['updated_at'] = date('Y-m-d H:i:s');
                $data['classify']['created_at'] = date('Y-m-d H:i:s');
                if($data['classify']['id']){
                    $res = $caseClassifyModel->where('id', $data['classify']['id'])->update($data['classify']);
                }else{
                    $res = $caseClassifyModel->insertGetId($data['classify']);
                }

                if ($res) {
                    return ['code' => 1, 'data' => '添加成功'];
                } else {
                    return ['code' => 0, 'data' => '添加失败'];
                }
                break;
            case 'edit':
                if (empty($data['classify']['name'])) {
                    return ['code' => 0, 'data' => '分类名不能为空'];
                }
//                if (empty($data['classify']['pic'])){
//                    return ['code' => 0,'data' => '分类图片不能为空'];
//                }
                if (empty($data['classify']['detail'])) {
                    return ['code' => 0, 'data' => '分类详情不能为空'];
                }
                $res = $caseClassifyModel->where('id', $data['classify']['id'])->update($data['classify']);
                if ($res) {
                    return ['code' => 1, 'data' => '修改成功'];
                } else {
                    return ['code' => 0, 'data' => '修改失败'];
                }
                break;
            case 'delete':
                if (isset($data['id'])) {
                    $res = $caseClassifyModel->where('id', $data['id'])->delete();
                    if ($res) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                }
                break;

        }
    }
    /**
     *案例列表
     */
    public function caseList(){

        return view('Admin.case.index');
    }
    /**
     *案例添加
     */
    public function caseAdd(){

        return view('Admin.case.add');
    }

    /**
     *案例数据接口
     */
    public function caseIndex(Request $request)
    {
        $data = $request->all();
        $videoCaseModel = new VideoCase();
        switch ($data['class']) {
            case 'select':
                $video = $videoCaseModel->join('case_classify', 'case_classify.id', '=', 'video_case.cid')
                    ->select('case_classify.name', 'video_case.*')
                    ->orderBy('id', 'desc')
                    ->paginate(15);
                if ($video) {
                    return ['code' => 1, 'data' => $video];
                } else {
                    return ['code' => 0, 'data' => '暂无案例'];
                }
                break;
            case 'classify':
                $classify = CaseClassify::select('id', 'name')->get()->toArray();
//                var_dump($classify);exit;
                if ($classify) {
                    return ['code' => 1, 'data' => $classify];
                } else {
                    return ['code' => 0, 'data' => '暂无分类'];
                }
                break;
            case 'find':
                if (isset($data['id'])) {
                    $detail = $videoCaseModel->where('id', $data['id'])->first();
                    if ($detail) {
                        return ['code' => 1, 'data' => $detail];
                    } else {
                        return ['code' => 0, 'data' => '案例不存在'];
                    }
                }
                break;
            case 'add':
                if (empty($data['case']['cid'])) {
                    return ['code' => 0, 'data' => '案例分类不能为空'];
                }
                if (empty($data['case']['case_name'])) {
                    return ['code' => 0, 'data' => '案例名称不能为空'];
                }

                if (empty($data['case']['detail'])) {
                    return ['code' => 0, 'data' => '请添加案例详情'];
                }
                if (empty($data['case']['pic'])) {
                    return ['code' => 0, 'data' => '请上传案例封面图'];
                }
                if (empty($data['case']['video'])) {
                    return ['code' => 0, 'data' => '请上传案例视频'];
                }
                if($data['case']['id']){
                    $res = $videoCaseModel->where('id', $data['case']['id'])->update($data['case']);
                }else{
                    $res = $videoCaseModel->create($data['case']);
                }

                if ($res) {
                    return ['code' => 1, 'data' => ' 设置成功'];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'delete':
                if (isset($data['id'])) {
                    $res = $videoCaseModel->where('id', $data['id'])->delete();
                    if ($res) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                }
                break;
        }
    }

    /**
     * 源头厂家信息列表
     */
    public function factory_index()
    {
        return view('Admin.factory.index');
    }
    /**
     * 添加源头厂家
     */
    public function add_factory()
    {
        return view('Admin.factory.add');
    }

    /**
     * 厂家数据接口
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function factory(Request $request)
    {
        $data = $request->all();
        $FactoryModel = new Factory();
        switch ($data['class']) {
            case 'select':
                $factory = $FactoryModel->orderBy('id', 'desc')->paginate(15);
                if ($factory) {
                    return ['code' => 1, 'data' => $factory];
                } else {
                    return ['code' => 0, 'data' => '暂无数据'];
                }
                break;
            case 'find':
                if (isset($data['id'])) {
                    $detail = $FactoryModel->where('id', $data['id'])->first();
                    if ($detail) {
                        return ['code' => 1, 'data' => $detail];
                    } else {
                        return ['code' => 0, 'data' => '厂家信息有误'];
                    }
                }
                break;
            case 'add':
                if (empty($data['factory']['factory_name'])) {
                    return ['code' => 0, 'data' => '厂家名称不能为空'];
                }
                if (empty($data['factory']['pic'])) {
                    return ['code' => 0, 'data' => '请上传封面图'];
                }
                if (empty($data['factory']['detail'])) {
                    return ['code' => 0, 'data' => '请添加厂家详情'];
                }
                if (empty($data['factory']['phone'])) {
                    return ['code' => 0, 'data' => '请添加联系电话'];
                }
                if (empty($data['factory']['management'])) {
                    return ['code' => 0, 'data' => '请添加经营类目'];
                }
                if(isset($data['factory']['id'])){
                    $res = $FactoryModel->where('id', $data['factory']['id'])->update($data['factory']);
                }else{
                    $res = $FactoryModel->create($data['factory']);
                }
                if ($res) {
                    return ['code' => 1, 'data' => ' 设置成功'];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'delete':
                if (isset($data['id'])) {
                    $res = $FactoryModel->where('id', $data['id'])->delete();
                    if ($res) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                }
                break;
        }
    }
}
